package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class BannerServiceImpl implements IBannerService {


    @Autowired
    private BannerRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ITravelService travelService;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        repository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        repository.save(banner);
    }

    @Override
    public Banner get(String id) {
        return repository.findById(id).orElse(null);
    }


    @Override
    public void saveOrUpdate(Banner banner) {
        if (banner == null){
            this.save(banner);
        }else {
            this.update(banner);
        }
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {

        // 查询对象
        Query query = new Query();

        // 查询条件
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        // 调用分页查询工具类
        Page<Banner> page = DBHelper.query(template, Banner.class, query, pageable);

        return page;
    }

    @Override
    public Map<String, Object> getAllType() {

        List<Strategy> sts = strategyService.list();

        List<Travel> ts = travelService.list();

        HashMap<String, Object> map = new HashMap<>();
        map.put("sts",sts);
        map.put("ts",ts);
        return map;
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public List<Banner> queryTravel() {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        List<Banner>  list = repository.findByType(Banner.TYPE_TRAVEL,pageable);
        return list;
    }

    @Override
    public Banner getStrategy() {

        List<Banner> list = repository.findByTypeAndSequence(Banner.TYPE_STRATEGY, 1);
        return list.get(0);
    }
}
